package com.sunyard.utils.msg;

import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Decoder;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

public class RSAUitls {
    private static final String ENCODING = "UTF-8";
    private static final String SIGNATURE_ALGORITHM = "SHA256withRSA";

    public static String encodeBase64(byte[] bytes) {
        return new String(Base64.encodeBase64(bytes));
    }

    /**
     * BASE64解码
     *
     * @param key
     * @return
     */
    public static byte[] decodeBase64(String key) {
        byte[] result = null;
        try {
            result = Base64.decodeBase64(key.getBytes(ENCODING));
        } catch (Exception e) {
            return null;
        }
        return result;
    }

    public static String sign256(String data, String privateKey) throws Exception {

        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initSign(getPrivateKey(privateKey));
        signature.update(data.getBytes(ENCODING));
        return encodeBase64(signature.sign());

    }

    public static PublicKey getPublicKey(String key) throws Exception {
        byte[] keyBytes;
        keyBytes = (new BASE64Decoder()).decodeBuffer(key);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(keySpec);
        return publicKey;
    }


    public static PrivateKey getPrivateKey(String key) throws Exception {
        byte[] keyBytes;
        keyBytes = (new BASE64Decoder()).decodeBuffer(key);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
        return privateKey;

    }

    public static boolean verify256(String data, String sign, String publicKey) {
        if (data == null || sign == null || publicKey == null) {
            return false;
        }
        try {
            Signature signetcheck = Signature.getInstance(SIGNATURE_ALGORITHM);
            signetcheck.initVerify(getPublicKey(publicKey));
            signetcheck.update(data.getBytes(ENCODING));
            return signetcheck.verify(decodeBase64(sign));
        } catch (Exception e) {
            return false;
        }
    }

    public static void main(String[] args) throws Exception {
        String privatekey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBANO36EfVfyO3ZWSCeVB9FehRbJ5Oq6648YxfzHjyEUim2gFu894zoizWRTLi0RPqTleBDAqax62GHRkXlXrkmGsD1QpSr2tOXLiEqOGJZc97lSb5WnY02xSygWGvorngMZbVdunBpZgT4cfhUdgSJ+qzJRhtW8ax1GM8S89m/0UFAgMBAAECgYBWo6TPeKPNtugsKGSCtp13c5Kyedkx6AcY/b8MI2tFQtplycTMQm70UD8DIuSSdMjYcDvAPzTFYuOXeBo4r0FbkwfZ+fzHE/vTr0EXjWcXyEutHeLr7iDJfKUQ4oPcJ/K0ExPLr6yQhiGpH4TMdYrlYtDNVc7X60eFr15PKD19AQJBAPHyS7rxWKfNhwP2Cf+YZdJ3KlrOl5kEPWEi7cAe5kXh5T+kDyf1DThxX9MmiTLxvn9WpA3p0ZKRWpZc2YU108ECQQDgBB/8mi5mzllwsWcFZooXqKtEdyN4JFDYv0ILoPjXbDmSdwJ3oQUDc7J9PbPSUmPHYx+1ThGzONR7tE7egbJFAkEAg5L4jBlj1R14JzdOCKmf9ezII8nlt1kO6BxOnwQuxiIqwYk+lMQ3BFLjgbibNBEzP5ymasqVJdfWI58qy76SAQJBALApbkIFuTGtWdZuG5a6oSOjxzMrAWCMJmucU8KzTpyRheCw5+bNYBTr2dP1PsDJe5+jSp8YCoFG0omJLHB7y4UCQB1M84v6NyNuAuLDMASAIB9h+eDnR4Q1kzOshXOp9DT5ZpfFS7SVlIGzTIHfBPRUGtBkeBrvbxalVfzRFVkzJD4=";
        Map<String, String> param = new HashMap<>();
        param.put("userId", "333434343");//用户id

        param.put("aaaa", "1234");

        param.put("2aaaa", "1234");

        param.put("1aaaa", "1234");

        param.put("termSn", "4314321432143");//终端序列号

        String md5Str = MD5Util.getMd5Str(param);

        System.out.println("md5Str:....." + md5Str);

        String signature = RSAUitls.sign256(md5Str, privatekey);
        System.out.println(signature);
    }
}
